import React from 'react'
import Markdown from '../markdown/index'

function MyCatalogue() {

  const [menuList, setMenuList] = React.useState([])

  React.useEffect(() => {

    let pathList = [{ id: '/', path: '/', parentPath: null }];
    let mdData = {};

    for (const key in Markdown) {
      if (Object.hasOwnProperty.call(Markdown, key)) {

        const path = Markdown[key];
        console.log(key, path);


        // 构建文件列表
        // 用 '/' 分割
        const split = key.split('/');
        if (split.length === 1) {
          pathList.push({ id: '/' + key, path: key, parentPath: '/' });
        } else if (split.length > 1) {
          for (let i = 0; i < split.length; i++) {
            const p = split[i];
            if (i === 0) {
              pathList.push({ id: '/' + p, path: p, parentPath: '/' });
            } else {
              const pp = split[i - 1];
              pathList.push({ id: '/' + pp + '/' + p, path: p, parentPath: pp });
            }
          }
        }

        // 获取文件内容
        const fetchPromise = fetchData(path).then(res => {
        })
      }
    }

    console.log('pathList', pathList)
    console.log('pathList去重', equalArray(pathList))
    pathList = equalArray(pathList);
    const menu = constructTree(pathList);
    console.log('menu', menu);
    setMenuList(menu);
  }, [])

  // https://www.cnblogs.com/lzkwin/p/12143458.html
  const idMapping = (data) => {
    return data.reduce((acc, el, i) => {
      acc[el.path] = i;
      return acc;
    }, {})
  };


  const equalArray = (arr) => {
    let obj = {};
    let result = [];
    for (var i = 0; i < arr.length; i++) {
      if (!obj[arr[i].id]) {
        result.push(arr[i]);
        obj[arr[i].id] = true;
      }
    }
    return result;
  }

  const constructTree = (data) => {

    const idMap = idMapping(data);

    let root;
    data.forEach(el => {
      // 判断根节点
      if (el.parentPath === null) {
        root = el;
        return;
      }
      // 用映射表找到父元素
      const parentEl = data[idMap[el.parentPath]];
      // 把当前元素添加到父元素的`children`数组中
      parentEl.children = [...(parentEl.children || []), el];
    });
    return root;
  }

  // 用 fetch 获取文件内容 fetch(path).then(res => res.text()).then(res => console.log('res', res))
  const fetchData = async (path) => {
    const response = await fetch(path);
    const res = await response.text();
    return res;
  }

  return (
    <div>
      <span>{menuList.toString()}</span>
    </div>
  )
}

export default MyCatalogue
